package com.sh169.action.user;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.sh169.beans.PageForm;
import com.sh169.beans.UserHolder;
import com.sh169.pojos.Collect;
import com.sh169.pojos.Product;
import com.sh169.pojos.RoleUserRelation;
import com.sh169.pojos.User;
import com.sh169.pojos.Vendor;
import com.sh169.util.BaseHttpFilter;
import com.sh169.util.Md5;

@At("/user")
@IocBean(name="userHomeAction")
@InjectName("userHomeAction")
public class HomeAction {
	@Inject("refer:dao")
	private Dao dao;
	public void setDao(Dao dao){
		this.dao = dao;
	}
	@At("/home")
	@Ok("tiles:user.home")
	public void home(HttpServletRequest request){
		
	}
	@At("/info/manage")
	@Ok("tiles:user.info.manage")
	public User manageUserInfo(HttpServletRequest request){
		UserHolder uh = (UserHolder) request.getSession().getAttribute(BaseHttpFilter.SECURITY_SESSION_USER);
		if(uh!=null){
			return dao.fetch(User.class,uh.getUsername());
		}
		return null;
	}
	@At("/info/update")
	@Ok("redirect:/user/info/manage")
	public void updateUserInfo(@Param("::user.")User user){
		User temp = dao.fetch(User.class,user.getId());
		if(temp != null){
			temp.setNickName(user.getNickName());
			temp.setAddress(user.getAddress());
			temp.setPhone(user.getPhone());
			temp.setTelephone(user.getTelephone());
			dao.update(temp);
		}
	}
	@At({"/password/update","/password/preupdate"})
	@Ok("tiles:user.password.update")
	public void updatePassword(HttpServletRequest request,@Param("pold")String passold,@Param("pnew1")String passnew1,@Param("pnew2")String passnew2){
		if(Strings.isEmpty(passold)){
			request.setAttribute("result", "error");
			return ;
		}
		if(Strings.isEmpty(passnew1)||Strings.isEmpty(passnew2)||!passnew1.equals(passnew2)||passnew1.length()<4||passnew1.length()>16){
			request.setAttribute("result","error");
			request.setAttribute("message", "新密码必须相同，且密码长度为4-16位");
		}else{
			UserHolder uh =(UserHolder) request.getSession().getAttribute(BaseHttpFilter.SECURITY_SESSION_USER);
			if(uh!=null){
				User temp = dao.fetch(User.class,uh.getUsername());
				if(!uh.getPassword().equals(Md5.encode(uh.getUsername()+passold))){
					request.setAttribute("result","error");
					request.setAttribute("message", "旧密码不对");
					return ;
				}
				temp.setPassword(Md5.encode(temp.getUsername()+passnew1));
				dao.update(temp);
				request.setAttribute("result","success");
				request.setAttribute("message", "修改成功");
			}
		}
			
		
	}
	@At("/collect/manage")
	@Ok("tiles:user.collect.manage")
	public PageForm<Collect> manageCollect(HttpServletRequest request,@Param("pageNum")int pageNum){
		PageForm<Collect> pf = new PageForm<Collect>();
		String username = ((UserHolder)request.getSession().getAttribute(BaseHttpFilter.SECURITY_SESSION_USER)).getUsername();
		User user = dao.fetch(User.class,username);
		Pager page = dao.createPager(pageNum<1?1:pageNum, 20);
		List<Collect> collects = dao.query(Collect.class, Cnd.where("fromUserid","=",user.getId()), page);
		for(Collect ct : collects){
			dao.fetchLinks(ct, "product");
			Product p = ct.getProduct();
			dao.fetchLinks(p, "vendor");
			dao.fetchLinks(p, "classify");
			dao.fetchLinks(p, "brand");
		}
		page.setRecordCount(dao.count(Collect.class));
		pf.setResultList(collects);
		pf.setPage(page);
		return pf;
	}
	@At("/collect/delete")
	@Ok("redirect:/user/collect/manage")
	public void deleteCollect(@Param("ids")int[] ids){
		if(ids!=null && ids.length>0){
			for(int id: ids)
				dao.delete(Collect.class, id);
		}
	}
	@At("/collect")
	public void collect(@Param("productid")int productid,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		if(dao.fetch(Collect.class,Cnd.where("productid","=",productid))==null && dao.fetch(Product.class,productid)!=null){
			UserHolder uh = (UserHolder) req.getSession().getAttribute(BaseHttpFilter.SECURITY_SESSION_USER);
			User user = dao.fetch(User.class,Cnd.where("username","=",uh.getUsername()));
			Collect c = new Collect();
			c.setCreateTime(new Date());
			c.setFromUserid(user.getId());
			c.setProductid(productid);
			dao.insert(c);
		}
		String url = req.getHeader("referer");
		if(!Strings.isEmpty(url))
			resp.sendRedirect(url);
		else{
			resp.sendRedirect("/");
		}
	}
	@At("/vendor/preregist")
	@Ok("tiles:vendor.regist")
	public String preRegistVendor(HttpServletRequest req){
		UserHolder uh = (UserHolder) req.getSession().getAttribute(BaseHttpFilter.SECURITY_SESSION_USER);
		User user = dao.fetch(User.class,uh.getUsername());
		if(user.getType() != User.TYPE_VENDOR){
			return "regist";
		}else{
			Vendor vendor = dao.fetch(Vendor.class, Cnd.where("userid","=",user.getId()));
			if(vendor.getVendorState()==User.STATE_VERIFY)
				return "verify";
			else
				return "success";
		}
	}
	@At("/vendor/regist")
	@Ok("tiles:vendor.regist")
	public String registVendor(@Param("::vendor.")Vendor vendor,HttpServletRequest req){
		UserHolder uh = (UserHolder) req.getSession().getAttribute(BaseHttpFilter.SECURITY_SESSION_USER);
		User user = dao.fetch(User.class,uh.getUsername());
		vendor.setId(0);
		vendor.setCreateTime(new Date());
		vendor.setUserid(user.getId());
		vendor.setVendorState(User.STATE_SUCCESS);
		dao.insert(vendor);
		user.setType(User.TYPE_VENDOR);
		dao.update(user);
		RoleUserRelation rur = new RoleUserRelation();
		rur.setRoleid("vendor");
		rur.setUserid(user.getId());
		dao.insert(rur);
		return "success";
	}
}
